/*
 * @Author: Wangjun
 * @Date: 2021-06-04 22:37:39
 * @LastEditTime: 2022-10-27 13:41:36
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \query\tables.go
 * hnxr
 */

package query

import (
	"bytes"
	"errors"
	"sort"
	"strings"
)

var mq = new(tables)

func init() {
	mq.mapQuery = map[string]*Table{}
	mq.registerFunction()
}

/**
 * @description:
 * @param {string} tableName
 * @param {*Query} table
 * @return {*}
 */
func RegisterTable(tableName string, table *Table) (err error) {
	if _, ok := mq.mapQuery[tableName]; ok {
		err = errors.New(tableName + " already exists")
		return
	}
	mq.mapQuery[tableName] = table
	return
}

// GetTableNames 获取表名列表
func GetTableNames() []string {
	cols := make([]string, 0, len(mq.mapQuery))
	for key := range mq.mapQuery {
		cols = append(cols, key)
	}
	return cols
}

// 获取指定的schema
func GetSchema(name ...string) string {
	buf := bytes.NewBuffer(nil)
	for key, query := range mq.mapQuery {
		buf.WriteString(key + ":\n\t")
		cols := query.Keys()
		sort.Strings(cols)
		buf.WriteString(strings.Join(cols, ",\n\t"))
		buf.WriteString("\n")
	}

	return buf.String()
}

/**
 * @description:
 * @param {string} tableName
 * @return {*}
 */
func GetTable(tableName string) *Table {
	t, ok := mq.mapQuery[tableName]
	if ok {
		return t
	}
	return nil
}

type tables struct {
	mapQuery map[string]*Table
	mapFunc  map[string]QueryFunc //函数注册
}

// 注册函数
func (m *tables) registerFunction() {
	m.mapFunc = map[string]QueryFunc{}
	m.mapFunc["GT"] = GT     //Greater than //大于
	m.mapFunc["GE"] = GE     //Greater than or equal to //大于等于
	m.mapFunc["LT"] = LT     //Less than //小于
	m.mapFunc["LE"] = LE     //Less than or equal to //小于等于
	m.mapFunc["NE"] = NE     //not equal to //不等于
	m.mapFunc["EQ"] = EQ     //equal to //等于
	m.mapFunc["IN"] = IN     //equal to //IN
	m.mapFunc["OrIN"] = OrIN //equal to //Or IN
	m.mapFunc["Like"] = Like
	m.mapFunc["Match"] = Match
	m.mapFunc["OrGT"] = OrGT
	m.mapFunc["OrGE"] = OrGE
	m.mapFunc["OrLT"] = OrLT
	m.mapFunc["OrLE"] = OrLE
	m.mapFunc["OrNE"] = OrNE
	m.mapFunc["OrEQ"] = OrEQ
	m.mapFunc["OrLike"] = OrLike
	m.mapFunc["Match"] = OrMatch

	m.mapFunc["Max"] = Max
	m.mapFunc["Min"] = Min
	m.mapFunc["Sum"] = Sum
	m.mapFunc["Avg"] = Avg
	m.mapFunc["Count"] = Count
	m.mapFunc["Mult"] = Mult
	m.mapFunc["Divi"] = Divi
	m.mapFunc["Add"] = Add
	m.mapFunc["Sub"] = Sub

	m.mapFunc["ColSum"] = ColSum         //列之间相加
	m.mapFunc["ColGtCount"] = ColGtCount //列之间满足条件的个数
	m.mapFunc["ColEqCount"] = ColEqCount //列之间满足条件的个数
	m.mapFunc["ColLtCount"] = ColLtCount //列之间满足条件的个数
	m.mapFunc["ColAdd"] = ColAdd         //列+
	m.mapFunc["ColSub"] = ColSub         //列-
	m.mapFunc["ColMult"] = ColMult       //列*
	m.mapFunc["IfGT"] = IfGT             //IF 大于
	m.mapFunc["IfEQ"] = IfEQ
	m.mapFunc["IfLT"] = IfLT
}
